import React, { Component } from 'react';
import { Button, Card, Table } from 'antd';
import {reqGetProducts,reqUpOrDownProduct} from "../../api/index"
class Product extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            products:[],
         }
    }
    initColumns=()=>{
        this.columns=[
            {
                title:"商品名称",
                dataIndex:"name",
            },
            {
                title:"商品描述",
                dataIndex:"desc",
            },
            {
                title:"价格",
                dataIndex:"price",
            },
            {
                title:"状态",
                // render:(product)=>(
                //     product.status==1?(<p><Button type="primary" onClick={()=>{this.updateProductstatus(product)}}>下架</Button><span>在售</span></p>):(<p><Button type="primary" onClick={()=>{this.updateProductstatus(product)}}>上架</Button><span>已下架</span></p>)
                // )
                render:(product)=>{
                    const {status,_id}=product
                    const newStatus=status===1?2:1
                    return(
                        <span>
                            <Button type="primary" onClick={()=>{this.updateProductstatus(_id,newStatus)}}>
                                {status===1?"下架":"上架"}
                            </Button>
                            <span>{status===1?"在售":"已下架"}</span>
                        </span>
                    )
                }
            },
            {
                title:"操作",
                render:(product)=>(
                    <span>
                        <a href="">详情</a>
                        <a href="">修改</a>
                    </span>
                )
            }
        ]
    }
    // 获取商品分页列表
    getproducts=async()=>{
    const result=await reqGetProducts()
    console.log(result);
    if(result.status==0){
       this.setState({products:result.data.list})
    }
  
    }
    // 更新商品状态
    updateProductstatus=async(productId,status)=>{
     const result=await reqUpOrDownProduct(productId,status)
     this.getproducts()
     console.log(result);
    }
    componentWillMount(){
        this.initColumns();
    }
    componentDidMount(){
        this.getproducts()
    }
    render() {
        const {products}=this.state
        console.log(products);
        const title=(<Button type="primary" icon="plus" onClick={()=>{this.props.history.push("/product/addupdate")}}>添加商品</Button>)
        return ( <Card title={title}>
           <Table 
           columns={this.columns}
           dataSource={products}
           rowKey="_id"
           >

           </Table>
        </Card> );
    }
}
 
export default Product;